package util

import (
	"context"
	"errors"
	"log"
	"net/http"
	"time"
)

// HttpSrvRun 使用 http.Server 内置的 Shutdown() 方法优雅地关机
func HttpSrvRun(addr string, hdl http.Handler, onClose func()) {
	srv := &http.Server{
		Addr:    addr,
		Handler: hdl,
	}
	if onClose != nil {
		srv.RegisterOnShutdown(onClose)
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	WaitQuit(func() {
		log.Println("Shutting down server...")
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		if err := srv.Shutdown(ctx); err != nil {
			log.Fatal("Server forced to shutdown: ", err)
		}
		log.Println("Server exiting")
	})
}
